package com.gexin.controller.system;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class Tree {

    public ArrayList<Integer> postorderTraversal(TreeNode root) {

        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode cur = root;
        TreeNode flag = null;
        ArrayList<Integer> ans = new ArrayList<Integer>(20);
        while (cur != null) {
            stack.push(cur);
            cur = cur.left;
        }
        while (!stack.isEmpty()) {
            cur = stack.pop();
            if (cur.right == null || cur.right == flag) {
                ans.add(cur.val);
                flag = cur;
            }
            else {
                stack.push(cur);
                cur = cur.right;
                while(cur != null) {
                    stack.push(cur);
                    cur = cur.left;
                }
            }
        }
        return ans;
    }
        /* 用来记录最新出栈的节点，
         * 如果当前节点的右儿子与flag相同，说明当前节点右子树已完成遍历
         */
   /*     int[] num = new int[] { 10, 18, 3, 8, 12, 2, 7 };
        // 前序遍历：根节点->左子树->右子树
        // 前序 10 3 2 8 7 18 12
        // 中序遍历：左子树->根节点->右子树
        // 中序 2 3 7 8 10 12 18
        // 后序遍历：左子树->右子树->根节点
        // 后序 2 7 8 3 12 18 10
        Tree t = new Tree();
        for (int i = 0; i < num.length; i++) {
            t.add(num[i]);
        }
        // System.out.println("debug");
        t.prevOrder(t.root, null);
        for (int i = 0; i < t.nodeOrder.size(); i++) {
            System.out.print(t.nodeOrder.get(i) + "\t");
        }
        // 10 3 2 8 7 18 12
        System.out.println("");
        t.inOrder(t.root, null);
        for (int i = 0; i < t.nodeOrder.size(); i++) {
            System.out.print(t.nodeOrder.get(i) + "\t");
        }
        // 2 3 7 8 10 12 18
        System.out.println("");
        t.lastOrder(t.root, null);
        for (int i = 0; i < t.nodeOrder.size(); i++) {
            System.out.print(t.nodeOrder.get(i) + "\t");
        }
        // 2 7 8 3 12 18 10
        System.out.println("");*/

 }
